﻿using MediatR; 
using PublicClass;
using S.Organization.Domian.Model;
using S.Organization.Infrastructure;
using S.Organization.Read.API.Application.Command.SubcultivationCommand;

namespace S.Organization.Read.API.Application.CommandHandler.SubcultivationCommandHandler
{
    public class GetSubcultivationCommandHandler:IRequestHandler<GetSubcultivationCommand,PageInfo<Subcultivation>>
    {
        private readonly IBaseRepository<Subcultivation> _repository;


        public GetSubcultivationCommandHandler(IBaseRepository<Subcultivation> repository)
        {
            _repository = repository;
        }

        public async Task<PageInfo<Subcultivation>> Handle(GetSubcultivationCommand request, CancellationToken cancellationToken)
        {
            var query = await _repository.AllAsync();
            //数据总条数
            int Count = query.Count();
            //总页数
            int Total = (int)Math.Ceiling(Count * 1.0 / (request.Size));
            if (request.SDtate!=null)
            {
                query = query.Where(x => x.ConversionDate>= request.SDtate);
            }       
            if (request.EDtate!=null)
            {
                query = query.Where(x => x.ConversionDate<= request.EDtate);
            }

            if (!string.IsNullOrEmpty(request.earNumber))
            {
                query = query.Where(x => x.RaisedSheep == request.earNumber);
            }

            var list = query.Skip((request.Index - 1) * request.Size).Take(request.Size);
            var res = list.OrderByDescending(x => x.SubcultivationId).ToList();


            PageInfo<Subcultivation> pageinfo = new PageInfo<Subcultivation>();
            pageinfo.totalCount = Total;
            pageinfo.pageCount = Count;
            pageinfo.datas = res;
            return pageinfo;
        }
    }
}
